#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 创建目录，复制要打包的文件
# 要打包的目录 app 及以下所有py文件  sh tool 目录 run.py cmd.py
import os, tarfile, sys, random, json
from shutil import copyfile, rmtree


BASEFOLDER = os.path.abspath('.')
temp_path = os.path.abspath('./monserver')

if os.path.isdir(temp_path):
    rmtree(temp_path)

os.mkdir(temp_path)


def add_file(root_path, tpath, py=False):
    '''
    递归函数，遍历该文档目录和子目录下的所有文件，获取其path
    '''
    files = os.listdir(root_path)
    for file in files:
        if not os.path.isdir(root_path + '/' + file):   # not a dir
            if py:
                if str(file).endswith('.py'):
                    copyfile(os.path.join(root_path, file), os.path.join(tpath, file))
            else:
                copyfile(os.path.join(root_path, file), os.path.join(tpath, file))
            # all_files.append(root_path + '/' + file)
        else:  # is a dir
            if not os.path.isdir(os.path.join(tpath,file)):
                os.mkdir(os.path.join(tpath,file))
            add_file((root_path+'/'+file), os.path.join(tpath, file), py)


os.mkdir(os.path.join(temp_path, 'adminApp'))
add_file(os.path.join(BASEFOLDER, 'adminApp'), os.path.join(temp_path,'adminApp'), True)
add_file(os.path.join(BASEFOLDER, 'adminApp', 'static'), os.path.join(temp_path,'adminApp','static'), False)
add_file(os.path.join(BASEFOLDER, 'adminApp', 'static', 'layer'), os.path.join(temp_path,'adminApp','static', 'layer'), False)
add_file(os.path.join(BASEFOLDER, 'adminApp', 'static', 'laydate'), os.path.join(temp_path,'adminApp','static', 'laydate'), False)
add_file(os.path.join(BASEFOLDER, 'adminApp', 'templates'), os.path.join(temp_path,'adminApp','templates'), False)
os.mkdir(os.path.join(temp_path,'logs'))

for i in ['monclient']:
    os.mkdir(os.path.join(temp_path,i))
    add_file(os.path.join(BASEFOLDER,i), os.path.join(temp_path,i))

for i in ['run.py', 'requirements.txt']:
    copyfile(os.path.join(BASEFOLDER, i), os.path.join(temp_path, i))

if os.path.isfile('./monserver.tar.gz'):
    os.remove('./monserver.tar.gz')


with tarfile.open('./monserver.tar.gz', "w:gz") as tar:
    tar.add(temp_path, arcname=os.path.basename(temp_path))

rmtree(temp_path)